<html>
  <head>
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="parseuri.js"></script>
    
    <script>

var requestTimeout = 1000 * 15;  // 5 seconds
var expiresDays = 30 * 1000 * 60 * 60 * 24; // 30 days
var bookmarkName = '[Delicious]';

var username = null;
var password = null;
var quering = null;

function init()
{
  toggleLoggedOutState();
  
  console.debug('searching bookmark');
  
  chrome.bookmarks.search(bookmarkName, function (bookmarks) {
    console.debug('found ' + bookmarks.length + ' bookmarks');
    
    for (var i=0; i<bookmarks.length; i++)
    {
      var bookmark = bookmarks[i];
      
      console.debug('found bookmark #' + bookmark.id + ', title=' + bookmark.title + ', url=' + bookmark.url);

      if (bookmark.title == bookmarkName)
      {
	var uri = parseUri(bookmark.url);
	
	console.debug('parsed uri: ' + uri + ', user=' + uri.user + ', pass=' + uri.password);
	
	username = decodeURIComponent(uri.user);
	password = decodeURIComponent(uri.password);
	
	if (username && password)
	{
	  $("#username").val(username);
	  $("#password").val(password);

	  login();
	  
	  break;
	}
      }
    }
  });
}

function toggleLoggedInState() {
  $("#notLoggedIn").hide();
  $("#loggedIn").show();
}

function toggleLoggedOutState() {
  $("#loggedIn").hide();
  $("#notLoggedIn").show();
}

function toggleProcessingState() {
  $("#login").attr("disabled", true);
  $("#indicator").show();
  $("#msg").hide();
}

function toggleProcessedState() {
  $("#login").attr("disabled", false);
  $("#indicator").hide();  
  quering = null;
}

function createDeliciousBookmark(encodedUsername, encodedPassword)
{
    console.debug('create bookmarks')
    chrome.bookmarks.create({'parentId': "1",'title': bookmarkName}, 
    function (folder){      
        var url = "https://" + encodedUsername + ":" + encodedPassword + "@api.del.icio.us/v1/posts/update";
        chrome.bookmarks.create({'parentId': folder.id, 'index': 0, 'title': bookmarkName, 'url': url}, function (bookmark) {
	    console.debug('bookmark #' + bookmark.id + ' created');
      });
    });
}

function login()
{
    username = $("#username").val();
    password = $("#password").val();

  var user = encodeURIComponent(username);
  var pass = encodeURIComponent(password);
  
  toggleProcessingState();
  
  startLogin(user, pass, 
  function() {
    
    chrome.bookmarks.search(bookmarkName, function (bookmarks) {
      
      for (var i=0; i<bookmarks.length; i++)
      {
        if (bookmarks[i].title == bookmarkName)
        {
          console.debug('removing ' + bookmarks[i].title + ' bookmark')
          chrome.bookmarks.removeTree(bookmarks[i].parentId);  
        }
      }

    });
  
    $("#account").html(username);
    
    toggleProcessedState();
    toggleLoggedInState();
    
    chrome.windows.getCurrent(function(win) {
      chrome.tabs.getSelected(win.id, function(tab) {
        query(tab);
          });
        });    
    }, 
    function(status) {
    username = password = null;
    
    toggleProcessedState();
    toggleLoggedOutState();
    
    $("#msg").html("fail to login: " + status).show();
  });
}

function startLogin(encodedUser, encodedPass, onSuccess, onError)
{  
  var url = "https://" + encodedUser + ":" + encodedPass + "@api.del.icio.us/v1/posts/update";

  console.log("login to delicious as " + encodedUser);
  console.log("url: " + url);
  
  $.ajax({
    url : url,
    type : "GET",
    dataType : "xml",
    timeout : requestTimeout,
    success : function(xmlDoc, status) {
      var node = xmlDoc.evaluate("/update[@time]", xmlDoc).iterateNext();
      
      if (node)
      {
	var lastlogin = node.getAttribute("time");
	
	console.log(decodeURIComponent(encodedUser) + " last login at @ " + lastlogin);
		
	onSuccess();
    createDeliciousBookmark(encodedUser, encodedPass);
      }
      else
      {
	onError(); 
      }
    },
    error : function(xhr, status, e) {
      console.error("exception: " + status);
      
      onError(status);
    }
  });
}

function switchUser()
{
  $("#username").val(username);
  $("#password").val(password);

  toggleLoggedOutState();
}

function isurl(url)
{
  var re = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
  
  return re.test(url);
}

function query(tab)
{
  if (username && password && isurl(tab.url))
  {
    toggleProcessingState();
    
    chrome.pageActions.enableForTab('TagPageAction', {tabId: tab.id, url: tab.url, title: "Click to tag page...", iconId: 0});
    
    console.log("enable page action for tab #" + tab.id + " " + tab.url);
    
    startQuery(tab.url, function(){
      toggleProcessedState();
    }, function (){
      toggleProcessedState(status);
      
      $("#msg").html("fail to query: " + status).show();
    });
  }    
}

chrome.tabs.onSelectionChanged.addListener(function(tabId, windowId) {
  chrome.tabs.get(tabId, function(tab) {
    console.log("switch to tab: " + tab.url);

    query(tab);
  });
});

chrome.tabs.onUpdated.addListener(function(tabId, changedProps) {
  chrome.tabs.get(tabId, function(tab) {
    console.log("update tab: " + tab.url);

    query(tab);
  });
});



function startQuery(url, onSuccess, onError)
{
  var api = "https://" + encodeURIComponent(username) + ":" + encodeURIComponent(password) + "@api.del.icio.us/v1/posts/get?url=" +
	    encodeURIComponent(url) + "&meta=yes";

  console.log("get tags for " + url);
  
  if (quering)
  {
    quering.abort();
    
    console.log("cancel the requesting query");
  }
  
  $("#tags").hide();
  
  quering = $.ajax({
    url : api,
    type : "GET",
    dataType : "xml",
    timeout : requestTimeout,
    success : function(xmlDoc, status) {
      var node = xmlDoc.evaluate("/posts/post[@tag]", xmlDoc).iterateNext();
      
      if (node)
      {
	var tags = node.getAttribute("tag").split(" ");
		
	console.log("get tags: " + tags);
	
	html = ""
	
	for (i=0; i<tags.length; i++)
	{
	  html += "<a href='http://delicious.com/" + username + "/" + tags[i] + "' target='_blank'>" + tags[i] + "</a>&nbsp;";
	}
	
	$("#tags").html(html).show();
      }
      
      onSuccess();
    },
    error : function(xhr, status, e) {
      console.error("exception: " + status);
      
      onError(status);
    }
  });
}

    </script>
  </head>
  <body onload="init()">
	<div class="toolstrip-button" onclick="window.open('http://del.icio.us/home/')"><img src="deliciousUp16.png" title="My Del.icio.us" /></div>
	<span id="notLoggedIn" style="display:none;">	  
	  Username: <input id="username" type="text"> &nbsp;
	  Password: <input id="password" type="password"> &nbsp;
	  <input type="button" id="login" value="Login" onclick="login()">	  
	</span>
	<span id="loggedIn">
	  <!--div class="toolstrip-button" onclick="add_delicious()"><img src="tagUp24.png" title="Bookmark on Del.icio.us" /></div-->
	  <span id="account" onclick="switchUser()"></span>&nbsp;
	</span>
	<span id="indicator" style="display:none;"><img src="indicator.gif" /></span>
	<span id="tags" style="display:none;">Tags</span>
	<span id="msg" style="color:red;display:none;">Message</span>
  </body>
</html>	